<template>
  <div class="add-wrap" v-loading="loading">
    <Breadcrumb :titles="titles"></Breadcrumb>
    <div class="body">
      <div class="project">
        <el-form
          :model="basicForm"
          label-position="top"
          :rules="basicRules"
          ref="basicFormRef"
        >
          <!-- 基本信息 -->
          <div class="project-part">
            <div class="project-part-title">供地信息</div>

            <el-row>
              <el-col :span="6">
                <el-form-item
                  label="项目名称"
                  prop="projectName"
                >
                  <el-input
                    v-model="basicForm.projectName"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="编码">
                  <el-input
                    v-model="basicForm.pictureNumber"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="供地面积(亩)">
                  <el-input
                    v-model="basicForm.supportArea"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="供地时间">
                  <el-date-picker
                    v-model="basicForm.supportTime"
                    type="date"
                    :disabled="isDetail"
                    placeholder="选择日期"
                  >
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="6">
                <el-form-item label="供地方式">
                  <el-select
                    v-model="basicForm.supportWay"
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in landSupplyOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="用地性质">
                  <el-select
                    v-model="basicForm.landUsage"
                    multiple
                    :disabled="isDetail"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in landUseOptions"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="交易金额(万元)">
                  <el-input
                    v-model="basicForm.tradeMoney"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item label="高新区实得金额(万元)">
                  <el-input
                    v-model="basicForm.actuallyMoney"
                    placeholder="请输入"
                    type="number"
                    :disabled="isDetail"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>

          <!-- 供地范围 -->
          <div class="project-part">
            <div class="project-part-title">供地范围</div>
            <!-- <el-row>
              <el-col>
                <el-form-item label="文件类型">
                  <el-radio-group
                    v-model="fileType"
                    :disabled="isDetail"
                  >
                    <el-radio label="geojson"></el-radio>
                    <el-radio label="shp"></el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row> -->

            <!-- <el-row
              :gutter="24"
              v-if="fileType === 'geojson'"
            >
              <el-col :span="24">
                <el-form-item
                  label="报征范围文件（geojson格式）"
                >
                  <el-input
                    v-model="basicForm.geojson"
                    placeholder="请输入"
                    :disabled="isDetail"
                  ></el-input>
                  <el-button
                    size="small"
                    class="preview-button"
                    @click="previewMap"
                    >地图预览</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row> -->

            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item
                  label="供地范围文件（shp格式）"
                >
                  <el-upload
                    action="#"
                    class="shp-upload"
                    :show-file-list="false"
                    :drag="false"
                    :on-change="onFileSelect"
                    :auto-upload="false"
                    v-if="!isDetail"
                    accept=".zip"
                  >
                    <span>
                      <span class="shp-upload-icon"></span>
                      <span class="shp-upload-text"
                        >点击上传</span
                      >
                    </span>
                  </el-upload>
                  <el-input
                    v-model="basicForm.geojson"
                    placeholder="支持输入geojson"
                    :disabled="isDetail"
                    clearable
                  ></el-input>
                  <el-progress
                    v-if="
                      progressNum !== 0 &&
                      progressNum !== 100
                    "
                    :percentage="progressNum"
                    color="#409eff"
                  ></el-progress>
                  <el-button
                    size="small"
                    class="preview-button"
                    @click="previewMap"
                    v-if="basicForm.geojson"
                    >地图预览</el-button
                  >
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
    </div>
    <div class="line" v-show="!isDetail">
      <el-button @click="saveInfo" class="save-btn"
        >保存</el-button
      >
    </div>

    <customizeDialog
      :visible="dialogMapVisible"
      @update:visible="dialogMapVisible = $event"
      ref="dialog"
      :title="`${headerTitle}`"
      :titleTip="`当前面积：${currentArea}m²`"
      :width="'1200px'"
      top="100px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :has-footer="false"
      customPadding="0px"
    >
      <div
        v-loading="mapLoading"
        element-loading-text="文件正在解析中，请稍后..."
      >
        <MapView
          :viewer-id="viewerId"
          :key="countMapLoad"
          @onload="onMapLoad"
        />
        <Utool
          :viewerId="viewerId"
          :position="{ top: '60px', right: '20px' }"
          :t="[]"
          :b="[
            {
              title: '初始位置',
              icon: 'dingwei'
            }
          ]"
          :showMore="false"
        ></Utool>
      </div>
    </customizeDialog>
  </div>
</template>

<script>
import Breadcrumb from '@/components/breadcrumb'
import { addLandSupply } from '@/api/dataManagement'
import MapView from '@/components/mapView'
import Utool from '@/components/utool/index-land'
import customizeDialog from '@/components/checkHistory/customizeDialog.vue'
import { dwgFileById } from '@/api/projectMessage'
import * as turf from '@turf/turf'
import {
  landUseOptions,
  landSupplyOptions
} from '@/utils/project/data'
import dayjs from 'dayjs'
import request from '@/utils/request'

let _layerManager, _viewer

export default {
  props: {
    pkid: String,
    title: String,
    data: Object,
    isEdit: {
      type: Boolean,
      default: false
    },
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  components: {
    Breadcrumb,
    MapView,
    Utool,
    customizeDialog
  },
  data() {
    return {
      basicForm: {
        pkid: '',
        projectName: '',
        pictureNumber: '',
        supportArea: '',
        landUsage: '',
        supportWay: '',
        supportTime: '',
        tradeMoney: '',
        actuallyMoney: '',
        geojson: ''
      },
      basicRules: {
        projectName: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          }
        ]
      },
      loading: false,
      props: { multiple: true },
      uploadLoading: false,
      progressNum: 0,
      dialogMapVisible: false,
      mapLoading: false,
      headerTitle: '',
      countMapLoad: 0,
      currentFeature: '',
      currentArea: 0,
      fileType: 'geojson',
      viewerId: 'dwgMap'
    }
  },
  computed: {
    titles() {
      return [this.title]
    },
    landUseOptions() {
      return landUseOptions
    },
    landSupplyOptions() {
      return landSupplyOptions
    }
  },
  watch: {},
  mounted() {
    if (this.pkid) {
      this.basicForm = JSON.parse(JSON.stringify(this.data))
      this.basicForm.landUsage
        ? (this.basicForm.landUsage =
            this.data.landUsage.split(','))
        : (this.basicForm.landUsage = [])
    }
  },
  methods: {
    // 保存信息
    saveInfo() {
      this.$refs.basicFormRef.validate((res) => {
        if (res) {
          if (this.basicForm.landUsage) {
            this.basicForm.landUsage =
              this.basicForm.landUsage.join(',')
          } else {
            this.basicForm.landUsage = ''
          }

          if (this.basicForm.supportTime) {
            this.basicForm.supportTime = dayjs(
              this.basicForm.supportTime
            ).format('YYYY-MM-DD')
          } else {
            this.basicForm.supportTime = ''
          }

          if (this.fileType === 'shp') {
            this.basicForm.geojson = this.basicForm.shpJson
          }
          addLandSupply(this.basicForm).then((res) => {
            if (res.success) {
              this.$message.success(
                this.pkid ? '编辑成功' : '保存成功'
              )
              this.$router.push({
                path: '/dataManagement/landManagement/landSupply/list',
                query: { refresh: Date.now() }
              })
            } else {
              this.$message.error(res.message)
            }
          })
        }
      })
    },

    // 上传文件
    onFileSelect(file) {
      // this.uploadLoading = true
      this.loading = true
      const data = new FormData()
      data.append('file', file.raw)
      request({
        method: 'post',
        url: '/pad/common/importData',
        data: data,
        onUploadProgress: (progressEvent) => {
          this.progressNum = parseInt(
            ((progressEvent.loaded / progressEvent.total) *
              100) |
              0,
            10
          )
        }
      })
        .then((res) => {
          if (res.success) {
            // const id = res.data.fileId
            // const geojson = res.data.geoJson
            // this.$set(this.basicForm, 'fileName', file.name)
            // this.$set(this.basicForm, 'shpFile', id)
            // this.$set(this.basicForm, 'shpJson', geojson)
            // this.$set(this.basicForm, 'geojson', geojson)
            this.basicForm.geojson = res.data
            this.$message.success('上传成功')
          } else {
            this.$message.error(res.message)
          }

          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    // 地图预览
    previewMap() {
      if (this.basicForm.geojson) {
        this.viewByGeojson()
        this.dialogMapVisible = true
      }
    },

    // 通过文件id预览
    previewMapById(id, geojsonStr) {
      this.headerTitle = '地图预览'
      this.mapLoading = true

      if (!geojsonStr) {
        dwgFileById(id)
          .then((res) => {
            if (res.success) {
              this.currentFeature = JSON.parse(res.data)
              const area = turf.area(this.currentFeature)
              this.currentArea = area ? area.toFixed(2) : 0
              // 更新地图预览
              this.countMapLoad++
            }
            this.mapLoading = false
          })
          .catch(() => {
            this.mapLoading = false
          })
      } else {
        this.currentFeature = JSON.parse(geojsonStr)
        const area = turf.area(this.currentFeature)
        this.currentArea = area ? area.toFixed(2) : 0
        // 更新地图预览
        this.countMapLoad++
        this.mapLoading = false
      }
    },

    // 通过geojson预览
    viewByGeojson() {
      this.currentFeature = JSON.parse(
        this.basicForm.geojson
      )
      const area = turf.area(this.currentFeature)
      this.currentArea = area ? area.toFixed(2) : 0
      // 更新地图预览
      this.countMapLoad++
      this.mapLoading = false
    },

    // 地图加载
    onMapLoad({ id, viewer }) {
      _viewer = viewer

      _viewer.scene.imageryLayers.addImageryProvider(
        new Cesium.TiandituImageryProvider({
          mapStyle: null,
          token: 'a49a9220798216424e34b531cb3fa5b2',
          url: 'https://t0.tianditu.gov.cn/img_w/wmts'
        }),
        0
      )
      const geojson = _viewer.dataSources.add(
        Cesium.GeoJsonDataSource.load(this.currentFeature)
      )
      _viewer.flyTo(geojson)
    }
  },
  watch: {
    'basicForm.fileName': function (val) {
      if (val === '') {
        this.basicForm.shpFile = ''
        this.basicForm.shpJson = ''
        this.basicForm.geojson = ''
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/form.scss';
.add-wrap {
  .body {
    display: flex;
    padding: 10px 0 0 20px;

    &-left {
      width: 70%;
      border-right: 1px solid #f1f1f1;
      overflow: scroll;
    }

    &-right {
      flex: 1;
      padding-left: 10px;
    }

    .top {
      display: flex;
      justify-content: space-between;
      align-items: baseline;
      padding-right: 10px;
    }
  }

  .shp-upload {
    cursor: pointer;
    height: 0px;
    ::v-deep .el-upload {
      position: relative !important;
      right: 0 !important;
      top: 0 !important;
      transform: none !important;
    }

    &-text {
      position: absolute;
      top: -49px;
      left: 260px;
      color: #00baff;
      min-width: 60px;
      line-height: 14px;
    }

    &-icon {
      position: absolute;
      width: 16px;
      height: 14px;
      top: -49px;
      left: 240px;
      background: url('~@/assets/images/wisdom-construction/upload-file.png');
      background-size: 100% 100%;
    }
  }

  .preview-button {
    position: absolute;
    top: 5px;
    left: 330px;
    background: #497fa3;
    border: 1px solid #497fa3;
    border-radius: 2px;
    color: white;
  }

  .line {
    display: flex;
    justify-content: center;
  }
}
</style>
